<script setup>
import { ref } from 'vue'
import { artAddChannelService, artUpdateChannelService } from '@/api/article.js'

//弹层显示
const dialogVisible = ref(false)
const open = async (row) => {
  dialogVisible.value = true
  //有id表示是编辑
  if (row.id) {
    //数据回显，将这一行的数据回显到表单中，顺带加上id，但是这里需要拆解，否则formModel和row将指向同一个对象,修改一个另一个也会跟着变
    formModel.value = { ...row }
    console.log(formModel.value)
  }
}
defineExpose({ open })

//表单校验
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { pattern: /^\S{1,10}$/, message: '输入1-10个非空字符', trigger: 'blur' }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-z0-9A-Z]{1,15}$/,
      message: '输入1-15个英文或数字',
      trigger: 'blur'
    }
  ]
}
//发送请求
const formRef = ref(null)
//通知父组件回显
const emit = defineEmits(['success'])
const onSumbit = async () => {
  await formRef.value.validate()
  if (formModel.value.id) {
    await artUpdateChannelService(formModel.value)
  } else {
    await artAddChannelService(formModel.value)
  }
  ElMessage({
    type: 'success',
    message: formModel.value.id ? '编辑成功' : '添加成功'
  })
  dialogVisible.value = false
  emit('success')
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '新增分类'"
    width="30%"
    label-width="auto"
  >
    <el-form
      label-width="100px"
      style="padding-right: 30px"
      :model="formModel"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="formModel.cate_name"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="formModel.cate_alias"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSumbit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
